import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_business_2003a/bean/cart_info_bean_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvider with ChangeNotifier {
  String? cartString = '[]'; //用于保存到sp当中的String
  List<CartInfoBeanResult> cartList = []; //从Sp中的json翻译过的数据源,用于提供给页面
  String key = 'cartInfo';
  bool isAllCheck = true;
  double allPrice = 0; //商品总价
  num allGoodsCount = 0; //所有选中商品的数量

  //存到sp中的方法
  save(goodsId, goodsName, count, price, imagesUrl, isCheck) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString(key); //获取持久化数据
    print('取cartString:$cartString');
    //判断cartString是否为空,为空就说明是第一次添加商品,或者cartInfo被清除了
    //如果有值,进行decode(编码,从一个String转换为一个json),也就是转换操作
    var temp = cartString == null ? [] : json.decode(cartString!);
    //把获取到的json转换为list
    List<Map> tampList = (temp as List).cast();
    //声明变量,用于判断购物车中是否存在此商品,通过goodsId来判断
    var isHave = false;
    int ival = 0; //用于循环的int
    allGoodsCount = 0;
    for (var element in tampList) {
      //进行循环,找出是否已经存在该商品,如果存在,进行数量+1,注意临时list需要+1,数据源list也需要+1
      if (element['goodsId'] == goodsId) {
        tampList[ival]['count'] = element['count'] + 1;
        cartList[ival].count = cartList[ival].count! + 1;
        isHave = true;
      }

      if (element['isCheck']) {
        allGoodsCount += cartList[ival].count!;
        setAllGoodsCount(allGoodsCount);
      }
      ival++;
    }

    //判断如果数据源中没有当前的商品,则添加一个新商品到list中和数据源中
    if (!isHave) {
      Map<String, dynamic> newGood = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'imagesUrl': imagesUrl,
        'count': count,
        'price': price,
        'isCheck': isCheck
      };
      tampList.add(newGood);
      cartList.add(CartInfoBeanResult.fromJson(newGood));
    }

    //数据操作完毕,把tampList转换为一个String
    cartString = json.encode(tampList).toString();
    sharedPreferences.setString(key, cartString!);
    print('cartString:$cartString');
    print('cartList:${cartList.toString()}');
    notifyListeners();
  }

  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove(key);
    allGoodsCount=0;
    cartList.clear();
    print('清空完成');
    notifyListeners();
  }

  //得到购物车中商品的方法
  getCartInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有的商品,这时是一个字符串
    cartString = sharedPreferences.getString(key);
    //将cartList进行初始化,方式数据混乱
    cartList = [];
    //判断得到的字符串中是否有值
    if (cartString == null) {
      cartList = [];
    } else {
      List<Map<String, dynamic>> tempList =
          (json.decode(cartString.toString()) as List).cast();
      isAllCheck = true;
      allPrice = 0;
      allGoodsCount = 0;
      for (var element in tempList) {
        if (element['isCheck']) {
          //需要计算总价
          allPrice += element['count'] * element['price'];
          //需要计算选中的数量
          allGoodsCount += element['count'];
        } else {
          isAllCheck = false;
        }
        cartList.add(CartInfoBeanResult.fromJson(element));
      }
    }
    print('cartString:$cartString');
    notifyListeners();
  }

  //修改单个item选中状态
  changeCheckState(CartInfoBeanResult cartInfoBeanResult) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有的商品,这时是一个字符串
    cartString = sharedPreferences.getString(key);
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
    int tempIndex = 0; //用于循环当前list的下标
    int changeIndex = 0; //

    for (var element in tempList) {
      if (element['goodsId'] == cartInfoBeanResult.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    }

    tempList[changeIndex] = cartInfoBeanResult.toJson(); //把对象转换为json进行赋值
    cartString = json.encode(tempList).toString();
    sharedPreferences.setString(key, cartString!);
    await getCartInfo();
  }

  //点击全选按钮的操作
  changeAllCheckBtnState(bool isCheck) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有的商品,这时是一个字符串
    cartString = sharedPreferences.getString(key);
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
    List<Map> newList = []; //用于组成新的持久化数据
    for (var item in tempList) {
      var newItem = item; //赋值新的变量,因为在Dart中不让循环时修改原值
      newItem['isCheck'] = isCheck;
      newList.add(newItem);
    }
    cartString = json.encode(newList).toString(); //形成字符串
    sharedPreferences.setString(key, cartString!);
    await getCartInfo();
  }

  //通过id删除购物车商品
  deleteOneGood(int goodsId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有的商品,这时是一个字符串
    cartString = sharedPreferences.getString(key);
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    int tempIndex = 0;
    int deleteIndex = 0;

    for (var element in tempList) {
      if (element['goodsId'] == goodsId) {
        deleteIndex = tempIndex;
      }
      tempIndex++;
    }
    tempList.removeAt(deleteIndex);
    cartString = json.encode(tempList).toString(); //形成字符串
    sharedPreferences.setString(key, cartString!);
    await getCartInfo();
  }

  //加减购物车item数量
  addOrReduceAction(CartInfoBeanResult cartInfoBeanResult, String todo) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //得到购物车中所有的商品,这时是一个字符串
    cartString = sharedPreferences.getString(key);
    List<Map> tempList = (json.decode(cartString.toString()) as List).cast();

    int tempIndex = 0;
    int changeIndex = 0;
    for (var item in tempList) {
      if (item['goodsId'] == cartInfoBeanResult.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    }
    if (todo == 'add') {
      cartInfoBeanResult.count = cartInfoBeanResult.count! + 1;
    } else if (cartInfoBeanResult.count! > 1) {
      cartInfoBeanResult.count = cartInfoBeanResult.count! - 1;
    }

    tempList[changeIndex] = cartInfoBeanResult.toJson();
    cartString = json.encode(tempList).toString(); //形成字符串
    sharedPreferences.setString(key, cartString!);
    await getCartInfo();
  }

  setAllGoodsCount(count) {
    allGoodsCount = count;
    notifyListeners();
  }
}
